#include "Medium.h"
namespace RayTracer
{
	bool Medium::Hit(const Ray & r, float t_min, float t_max, HitRecord & rec) const
	{
		const bool enableDebug = false;
		const bool debugging = enableDebug && Random01() < 0.00001;

		HitRecord rec1, rec2;

		if (!boundary->Hit(r, -infinity, infinity, rec1))
			return false;

		if (!boundary->Hit(r, rec1.t + 0.0001, infinity, rec2))
			return false;

		if (debugging) std::cerr << "\nt_min=" << rec1.t << ", t_max=" << rec2.t << '\n';

		if (rec1.t < t_min) rec1.t = t_min;
		if (rec2.t > t_max) rec2.t = t_max;

		if (rec1.t >= rec2.t)
			return false;

		if (rec1.t < 0)
			rec1.t = 0;

		const auto ray_length = r.direction().length();
		const auto distance_inside_boundary = (rec2.t - rec1.t) * ray_length;
		const auto hit_distance = neg_inv_density * log(Random01());

		if (hit_distance > distance_inside_boundary)
			return false;

		rec.t = rec1.t + hit_distance / ray_length;
		rec.position = r.at(rec.t);

		rec.normal = vec3(1, 0, 0);  // arbitrary
		rec.front_face = true;     // also arbitrary
		rec.matPtr = phase_function;

		return true;
	}
}